<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}产品分类`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="商品名字" prop="name">
        <el-input v-model="drawerProps.row!.name" placeholder="请填写商品名字" clearable></el-input>
      </el-form-item>
      <el-form-item label="商品编码" prop="code">
        <el-input v-model="drawerProps.row!.code" disabled></el-input>
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input v-model="drawerProps.row!.price" placeholder="请填写商品价格" clearable></el-input>
      </el-form-item>
      <el-form-item label="商品成色" prop="conditionName">
        <el-select placeholder="选择商品成色" v-model="drawerProps.row!.conditionName">
          <el-option v-for="condition in conditions" :key="condition.id" :value="condition.name">
            {{ condition.name }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品库存" prop="stock">
        <el-input v-model="drawerProps.row!.stock" placeholder="请填写商品库存" clearable></el-input>
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryName">
        <el-select placeholder="选择商品分类" v-model="drawerProps.row!.categoryName">
          <el-option v-for="ca in cas" :key="ca.id" :value="ca.name">
            {{ ca.name }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品描述" prop="desc">
        <el-input v-model="drawerProps.row!.desc" type="textarea" placeholder="请填写商品描述"></el-input>
      </el-form-item>
      <el-form-item label="商品图片" prop="pictures">
        <UploadImgs v-model:file-list="drawerProps.row!.pictures" :limit="4" height="100px" width="100px">
          <template #empty>
            <el-icon>
              <Picture />
            </el-icon>
            <span>请上传图片</span>
          </template>
          <template #tip>至少上传 1 张照片 最多上传 4 张照片</template>
        </UploadImgs>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="GoodsDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Goods } from "@/api/interface";
import { Picture } from "@element-plus/icons-vue";
import { getCategorySubList } from "@/api/modules/category";
import UploadImgs from "@/components/Upload/Imgs.vue";
import { getGoodsConditions } from "@/api/modules/goods";

const rules = reactive({
  name: [{ required: true, message: "请填写商品名字" }],
  categoryName: [{ required: true, message: "请选择商品分类" }],
  pictures: [{ required: true, message: "请选择图片" }],
  price: [
    { required: true, message: "请填写价格" },
    {
      validator: customPriceValidator,
      message: "价格必须符合规则"
    }
  ],
  desc: [{ required: true, message: "请填写商品描述" }],
  conditionName: [{ required: true, message: "请选择商品成色" }],
  stock: [{ required: true, message: "请填写商品库存" }]
});

// 自定义价格验证函数
function customPriceValidator(rule: any, value: string, callback: (error?: string) => void) {
  const price = parseFloat(value);
  // 检查是否是有效的数字，并且大于零
  if (isNaN(price) || price <= 0) {
    callback("价格必须是大于零的数字");
  } else {
    // 提取小数部分
    const decimalPart = value.toString().split(".")[1];
    if (!decimalPart || decimalPart.length <= 2) {
      // 如果小数部分不存在或小于等于两位，则通过验证
      callback();
    } else {
      // 如果小数部分超过两位，则必须精确到两位
      if (decimalPart.length > 2) {
        callback("小数部分超过两位，必须精确到两位");
      } else {
        callback();
      }
    }
  }
}

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Goods.ResGoods>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  getCas();
  getConditions();
};

const cas = ref();
const getCas = async () => {
  const { data } = await getCategorySubList();
  cas.value = data;
};

const conditions = ref();
const getConditions = async () => {
  const { data } = await getGoodsConditions();
  conditions.value = data;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}商品成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
